package gov.pbc.nn.kjgl.task.dao;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

import com.bstek.bdf2.core.business.IUser;
import com.bstek.bdf2.core.context.ContextHolder;
import com.bstek.bdf2.core.orm.ParseResult;
import com.bstek.dorado.data.provider.Criteria;
import com.bstek.dorado.data.provider.Page;

import gov.pbc.nn.core.bdf.IUserSelect;
import gov.pbc.nn.core.bdf.service.UserService.DefaultUserRowMapper;
import gov.pbc.nn.core.dao.PbcnnCoreHibernateDao;
import gov.pbc.nn.core.dao.PbcnnCoreJdbcDao;

@Component("userSelectDeptDao")
public class UserSelectDeptDao implements IUserSelect {

	@Resource(name=PbcnnCoreJdbcDao.BEAN_ID)
	private PbcnnCoreJdbcDao jdbcDao;
	@Override
	public void loadUsers(Page<IUser> page, Criteria criteria, Map<String, Object> params) throws Exception {
		// TODO Auto-generated method stub
//		String deptId=ContextHolder.getLoginUser().getDepts().get(0).getId();
//		String sql = "SELECT\n"
//				+ "	U.*\n"
//				+ "FROM\n"
//				+ "	T_USER U\n"
//				+ "INNER JOIN BDF2_USER_DEPT UD ON UD.USERNAME_ = U.USERNAME_\n"
//				+ "WHERE\n UD.DEPT_ID_ = :deptId ";
//		Map<String, Object> valueMap = new HashMap<String, Object>();
//		valueMap.put("deptId", deptId);
//		PbcnnCoreJdbcDao jdbc = ContextHolder.getBean(PbcnnCoreJdbcDao.BEAN_ID);
//		ParseResult result = jdbc.parseCriteria(criteria, true, "U");
//		if(result!=null){			
//			sql += " AND "+result.getAssemblySql().toString() ;
//			valueMap.putAll(result.getValueMap());
//			jdbc.pagingQuery(page, sql,	new DefaultUserRowMapper(),valueMap);
//		}
//		else{
//			jdbc.pagingQuery(page, sql , new DefaultUserRowMapper(),valueMap);
//			//System.out.println(page.getEntities().size());
//		}
		String deptId=ContextHolder.getLoginUser().getDepts().get(0).getId();

		String sql = "SELECT\n"
				+ "	T.*\n"
				+ "FROM\n"
				+ "	(\n"
				+ "		SELECT\n"
				+ "			U.*, D.ID_ AS DEPT_ID_,D.NAME_ AS DEPT_NAME_\n"
				+ "		FROM\n"
				+ "			t_user U\n"
				+ "		LEFT JOIN bdf2_user_dept UD ON U.USERNAME_ = UD.USERNAME_\n"
				+ "		LEFT JOIN t_dept D ON UD.DEPT_ID_ = D.ID_ order by D.ID_,U.USERNAME_\n"
				+"	) T\n" +
				"WHERE\n" +
				"	T.DEPT_ID_ like :deptId ";
		ParseResult result = jdbcDao.parseCriteria(criteria, true, "T");
		if (result != null) {
			StringBuffer sb = result.getAssemblySql();
			Map<String, Object> valueMap = result.getValueMap();
			valueMap.put("deptId", deptId+"%");
			sql += " and "+sb.toString() ;
			jdbcDao.pagingQuery(page, sql,
					new DefaultUserRowMapper(),valueMap);
		} else {
			Map<String,Object> parameter = new HashMap<String,Object>();
			parameter.put("deptId", deptId+"%");
			jdbcDao.pagingQuery(page,  sql,new DefaultUserRowMapper(),parameter);
		}

	}

}
